<?php

namespace App\Dao\Task;

use App\Model\Exam\Exam;
use App\Model\Task\Task;
use Yj\Daos\BaseDao;
use Yj\Daos\Verify;

/**
 * @var Task
 */
class TaskDao extends BaseDao
{
    public function DaoWhereStatus($status)
    {
        return $this->getDaoQuery(['status' => $status], function (Verify $verify) {
            $verify('status', [null, 'all'], function ($query, $status) {
                $query->where('status', $status);
            });

        });
    }

    public function DaoWhere(array $params)
    {
        return $this->getDaoQuery($params, function (Verify $verify) {
            $verify('id', function ($query, $id) {
                $query->where('id', $id);
            });
            $verify('title', function ($query, $title) {
                $query->where('title', 'like', '%' . $title . '%');
            });
            $verify('black_task_id', function ($query, $black_task_id) {
                if ($black_task_id) {
                    $query->whereNotIn('id', $black_task_id);
                }
            });
            $verify('keyword', [null, ""], function ($query, $keyword) {
                $query->where(function ($query) use ($keyword) {
                    $query->orWhere('product_name', 'like', '%' . $keyword . '%');
                    $query->orWhere('title', 'like', '%' . $keyword . '%');
                });
            });
            $verify('types', function ($query, $types) {
                $query->where('types', $types);
            });
            $verify('task_types_id', [null, 0], function ($query, $types) {
                $query->where('task_types_id', $types);
            });
            $verify('user_id', function ($query, $user_id) {
                $query->where('user_id', $user_id);
            });
            $verify('task_id', function ($query, $task_id) {
                $query->where('id', $task_id);
            });
            $verify('is_recomment', function ($query, $task_id) {
                $query->where('recomment_time', '>', 0);
            });
        });
    }

    public function changeStock(int $task_id, int $stock, string $reason)
    {
        return $this->DaoWhere([
            'id' => $task_id
        ])->increment('stock', $stock);
    }

    public function statistics(int $usersId)
    {
        $this->where('users_id', $usersId)->first();

    }

    public function getTotal($user_id, int $status): int
    {
        return $this->where('user_id', $user_id)->where('status', $status)->count();
    }

    public function setField(int $id, string $field, int $value)
    {
        $data = $this->where('id', $id)->firstOrError();
        $update = [$field => $value];

        if ($field == 'pay_status') {
            if ($data->status == 0 || $data->status == 1) {
                $update['status'] = $value;
            }
        }
        $data->fill($update);
        return $data->save();
    }


}